package com.wtwd.campus.utils;


import com.wtwd.campus.common.Constants;
import com.wtwd.campus.service.RedisService;
import org.apache.commons.lang.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class CommandNumberUtil {
    //加锁防止序列号重复
    public static synchronized String generateDeviceCommandNumber(RedisService redisService) {
        String commandNumber = "";
        String lastNumber = redisService.getValue(Constants.SEND_DEVICE_REDIS_KEY);
        if(StringUtils.isBlank(lastNumber)) {
            commandNumber = "0001";
        }else {
            if(lastNumber.equals("FFFE")) { // FFFF为转换管理员使用，因为该指令比较特殊，涉及到两行的修改
                commandNumber = "0001";
            }else {
                int lastNumberInt = BinaryUtil.hexString2Int(lastNumber);
                lastNumberInt = lastNumberInt + 1;
                commandNumber = BinaryUtil.int2fourCharHexStr(lastNumberInt);
            }
        }
        redisService.setKey(Constants.SEND_DEVICE_REDIS_KEY,commandNumber,0L, TimeUnit.MINUTES);
        return commandNumber;
    }

    /**
     * 创建设备时分秒式的流水号
     * @return
     */
    public static  String getCurTime() {
        Date d = new Date();
        SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");
        String format = sbf.format(d);
        String[] split = format.split(":");
        String time = split[0].concat(split[1]).concat(split[2]);
        return time;
    }
}
